package cn.senwill.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.senwill.domain.Result;
import cn.senwill.domain.entity.User;
import cn.senwill.mapper.UserMapper;
import cn.senwill.service.UserService;
import cn.senwill.utils.JwtUtil;
import cn.senwill.utils.RandomStringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public Result registry(JSONObject jsonObject) {
        String username = String.valueOf(jsonObject.get("username"));
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            return Result.success("该用户账号已被注册", user);
        }
        String password = String.valueOf(jsonObject.get("password"));
        String salt = RandomStringUtil.generator(5);
        String md5Password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        Date date = new Date();
        User newUser = new User(null, username, md5Password, salt, date, date, 1);
        userMapper.insert(newUser);
        return Result.success("注册成功 ~", newUser);
    }

    @Override
    public Result login(JSONObject jsonObject) {
        String username = String.valueOf(jsonObject.get("username"));
        String password = String.valueOf(jsonObject.get("password"));
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        String md5Password = DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes());
        if (!md5Password.equals(user.getPassword())) {
            return Result.success("用户或密码错误", user);
        }
        String token = JwtUtil.createToken(user.getId());
        log.info("登录成功，请保管好您的令牌：{}", token);
        Map<String, Object> userInfoMap = BeanUtil.beanToMap(user, new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        return Result.success("登录成功 ~", userInfoMap);
    }

    @Override
    public Result getUserInfo(String token) {
        return Result.success("获取成功 ~", 666);
    }
}